<script lang="ts" setup>
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
import type { DnsRecordItem } from '@/apis/model/dns'
import { Message } from '@arco-design/web-vue'
import { pick } from 'lodash-es'
import {
  getDnsAuthorityNodeApi,
  postDnsAuthorityNodeApi,
  updateDnsAuthorityNodeApi,
} from '@/apis/modules/dns'

interface IProps {
  record: DnsRecordItem
}
const props = defineProps<IProps>()
const emit = defineEmits(['reload'])
const visible = defineModel<boolean>('visible', { required: true })
const formRef = ref<FormInstance>()
const title = computed(() => (props.record?.id ? '编辑节点' : '新建节点'))
const formState = reactive({
  name: '',
  ip: '',
})
const rules = computed<{ [key: string]: FieldRule[] }>(() => {
  const res = {
    name: [{ required: true, message: '节点名称不能为空', trigger: 'blur' }],
  }
  if (props.record?.id) {
    res.ip = [
      {
        required: true,
        validator(value, callback) {
          if (!value)
            return callback('节点 IP 不能为空')
          if (regexpMap.domain.test(value) || regexpMap.ipv4.test(value))
            return callback()
          callback('节点 IP 格式不正确')
        },
        trigger: 'blur',
      },
    ]
  }
  return res
})
const loading = ref(false)
async function getDetail() {
  await getDnsAuthorityNodeApi({ id: props.record.id }).then((res) => {
    Object.assign(formState, { ...pick(res, ['id', 'name', 'ip']) })
  })
}
async function handleSubmit() {
  const error = await formRef.value?.validate()
  if (error)
    return false
  const apiPath = props.record?.id
    ? updateDnsAuthorityNodeApi
    : postDnsAuthorityNodeApi
  loading.value = true
  const data = {
    ...formState,
    ip: props.record?.id ? formState.ip : undefined,
  }
  await apiPath(data)
    .then(() => {
      Message.success('操作成功')
    })
    .finally(() => (loading.value = false))
}
function handleOpen() {
  getDetail()
}
function handleClose() {
  formRef.value?.resetFields()
  emit('reload')
}
</script>

<template>
  <resource-dialog
    v-model:visible="visible"
    :title="title"
    :width="480"
    ok-text="保存"
    :mask-closable="false"
    :before-ok="handleSubmit"
    :before-open="handleOpen"
    :before-close="handleClose"
  >
    <a-form
      ref="formRef"
      layout="vertical"
      :model="formState"
      :rules="rules"
    >
      <a-form-item
        label="节点名称"
        field="name"
        asterisk-position="end"
      >
        <a-input
          v-model="formState.name"
          :max-length="32"
          show-word-limit
          placeholder="请输入节点名称"
        />
      </a-form-item>
      <a-form-item
        v-if="props.record?.id"
        label="节点 IP"
        field="ip"
        asterisk-position="end"
      >
        <a-input
          v-model="formState.ip"
          max-length="32"
          placeholder="请输入节点 IP"
        />
      </a-form-item>
    </a-form>
  </resource-dialog>
</template>

<style lang="less" scoped></style>
